package com.xiaoshuidi.cloud.module.iot.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.AddPasswordModelVo;
import com.xiaoshuidi.cloud.module.iot.common.ResultModel;
import com.xiaoshuidi.cloud.module.iot.controller.admin.doorlock.vo.OperateThirdDeviceRequestModel;
import com.xiaoshuidi.cloud.module.iot.controller.admin.doorlock.vo.OperateThirdDeviceResponseModel;
import com.xiaoshuidi.cloud.module.iot.dal.model.AccessTokenRequestWrapperModel;
import com.xiaoshuidi.cloud.module.iot.dal.model.AccessTokenResponseWrapperModel;
import com.xiaoshuidi.cloud.module.iot.dal.model.doorLock.*;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbAccountDo;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbDeviceDo;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbDoorlockPassword;
import com.xiaoshuidi.cloud.module.iot.dal.repository.DeviceOperationRepository;
import com.xiaoshuidi.cloud.module.iot.dal.repository.DeviceRepository;
import com.xiaoshuidi.cloud.module.iot.dal.repository.TbAccountRepository;
import com.xiaoshuidi.cloud.module.iot.dal.repository.TbDoorLockPasswordRepository;
import com.xiaoshuidi.cloud.module.iot.enums.*;
import com.xiaoshuidi.cloud.module.iot.service.DoorLockService;
import com.xiaoshuidi.cloud.module.iot.service.LocalAccessTokenServcie;
import com.xiaoshuidi.cloud.module.iot.service.ThirdInstanceFactory;
import com.xiaoshuidi.cloud.module.iot.service.ThirdInstanceService;
import com.xiaoshuidi.cloud.module.rooms.api.sdiot.IotRoomDeviceApi;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomDoorlockCdkeyVo;
import com.xiaoshuidi.cloud.module.system.api.sms.SmsSendApi;
import com.xiaoshuidi.cloud.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <br>
 *
 * @author Porter
 * create by 2019/6/27
 * @Emial Porter.Wang@ixiaoshuidi.com
 */
@Service
public class DoorLockServiceImpl implements DoorLockService {
    private static final Logger LOGGER = LoggerFactory.getLogger(DoorLockServiceImpl.class);

    @Autowired
    private LocalAccessTokenServcie localAccessTokenServcie;

    @Autowired
    private DeviceOperationRepository deviceOperationDataAccess;

    @Autowired
    private DeviceRepository deviceDataAccess;
    @Autowired
    private TbDoorLockPasswordRepository doorLockPasswordDataAccess;
    @Autowired
    private TbAccountRepository tbAccountDataAccess;
    @Resource
    private SmsSendApi smsFeignService;
    @Resource
    private IotRoomDeviceApi iotRoomDeviceApi;
//
//    @Value("${permanentPasswordTime.startTime}")
//    private String startTime;
//
//    @Value("${permanentPasswordTime.endTime}")
//    private String endTime;

    public ThreadPoolExecutor singleCoreThreadExecutor = new ThreadPoolExecutor(1, Runtime.getRuntime().availableProcessors() * 4,
            2, TimeUnit.MINUTES, new ArrayBlockingQueue<>(16), new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread asyncThread = new Thread(r);
            asyncThread.setName("琨山门锁设备删除密码异步任务 - " + new Date());
            return asyncThread;
        }
    }, new ThreadPoolExecutor.CallerRunsPolicy());


    public ResultModel<OperateThirdDeviceResponseModel> updatePassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        LOGGER.info("修改密码请求参数：{}", JSONObject.toJSONString(operateThirdDeviceRequestModel));
        AccessTokenRequestWrapperModel accessTokenRequestWrapperModel = new AccessTokenRequestWrapperModel();
        accessTokenRequestWrapperModel.setApiNo(operateThirdDeviceRequestModel.getApiNo());
        ResultModel<AccessTokenResponseWrapperModel> resultModel = localAccessTokenServcie.getAccessToken(accessTokenRequestWrapperModel);
        ThirdInstanceService thirdInstanceService = ThirdInstanceFactory.produce(operateThirdDeviceRequestModel.getBrand());
        operateThirdDeviceRequestModel.setAccessToken(resultModel.getData().getAccessToken());
        operateThirdDeviceRequestModel.setLoginName(resultModel.getData().getAppId());
        operateThirdDeviceRequestModel.setLoginKey(resultModel.getData().getAppKey());
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = thirdInstanceService.updateDoorLockPassword(operateThirdDeviceRequestModel);
        LOGGER.info("修改密码返回参数：{}", JSONObject.toJSONString(operateThirdDeviceResponseModel));
        return ResultModel.createSuccess(operateThirdDeviceResponseModel);
    }


    public ResultModel<OperateThirdDeviceResponseModel> unfrozenPassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        LOGGER.info("解冻密码请求参数：{}", JSONObject.toJSONString(operateThirdDeviceRequestModel));
        AccessTokenRequestWrapperModel accessTokenRequestWrapperModel = new AccessTokenRequestWrapperModel();
        accessTokenRequestWrapperModel.setApiNo(operateThirdDeviceRequestModel.getApiNo());
        ResultModel<AccessTokenResponseWrapperModel> resultModel = localAccessTokenServcie.getAccessToken(accessTokenRequestWrapperModel);
        ThirdInstanceService thirdInstanceService = ThirdInstanceFactory.produce(operateThirdDeviceRequestModel.getBrand());
        operateThirdDeviceRequestModel.setAccessToken(resultModel.getData().getAccessToken());
        operateThirdDeviceRequestModel.setLoginName(resultModel.getData().getAppId());
        operateThirdDeviceRequestModel.setLoginKey(resultModel.getData().getAppKey());
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = thirdInstanceService.unfrozenDoorLockPassword(operateThirdDeviceRequestModel);
        LOGGER.info("解冻密码返回参数：{}", JSONObject.toJSONString(operateThirdDeviceResponseModel));
        return ResultModel.createSuccess(operateThirdDeviceResponseModel);
    }

    public ResultModel<OperateThirdDeviceResponseModel> deletePassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        LOGGER.info("删除密码请求参数：{}", JSONObject.toJSONString(operateThirdDeviceRequestModel));
        AccessTokenRequestWrapperModel accessTokenRequestWrapperModel = new AccessTokenRequestWrapperModel();
        accessTokenRequestWrapperModel.setApiNo(operateThirdDeviceRequestModel.getApiNo());
        ResultModel<AccessTokenResponseWrapperModel> resultModel = localAccessTokenServcie.getAccessToken(accessTokenRequestWrapperModel);
        AccessTokenResponseWrapperModel accessTokenResponseWrapperModel = resultModel.getData();
        ThirdInstanceService thirdInstanceService = ThirdInstanceFactory.produce(operateThirdDeviceRequestModel.getBrand());
        operateThirdDeviceRequestModel.setAccessToken(accessTokenResponseWrapperModel.getAccessToken());
        operateThirdDeviceRequestModel.setLoginName(accessTokenResponseWrapperModel.getAppId());
        operateThirdDeviceRequestModel.setLoginKey(accessTokenResponseWrapperModel.getAppKey());
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = thirdInstanceService.deleteDoorLockPassword(operateThirdDeviceRequestModel);
        LOGGER.info("删除密码返回参数：{}", JSONObject.toJSONString(operateThirdDeviceResponseModel));
        return ResultModel.createSuccess(operateThirdDeviceResponseModel);
    }


    @Override
    public ResultModel<PageInfo<DoorLockReportRespVO>> getOpenDoorRecord(DoorLockReportReqVO doorLockReportReqVO) {
        TbDeviceDo tbDeviceDo = deviceDataAccess.getDeviceByDeviceNo(doorLockReportReqVO.getDeviceNo());
        if (tbDeviceDo == null) {
            //设备不存在
            return ResultModel.createFail(ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getCode(), ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getMsg());
        }
        PageInfo<DoorLockReportRespVO> tbDeviceOperationPageInfo = deviceOperationDataAccess.getOpenDoorRecord(doorLockReportReqVO);
        List<DoorLockReportRespVO> doorLockReportRespVOS = tbDeviceOperationPageInfo.getList();
        for (DoorLockReportRespVO doorLockReportRespVO : doorLockReportRespVOS) {
            if (StrUtil.isNotBlank(doorLockReportRespVO.getName())) {
                TbDoorlockPassword tbDoorlockPassword = new TbDoorlockPassword();
                try {
                    tbDoorlockPassword.setId(Integer.valueOf(doorLockReportRespVO.getName()));
                } catch (Exception e) {
                    //脏数据处理
                    tbDoorlockPassword.setThirdPasswordId(doorLockReportRespVO.getName());
                }
                tbDoorlockPassword.setDeviceNo(doorLockReportReqVO.getDeviceNo());
                tbDoorlockPassword = doorLockPasswordDataAccess.selectTbDoorlockPassword(tbDoorlockPassword);
                if (tbDoorlockPassword != null) {
                    doorLockReportRespVO.setName(tbDoorlockPassword.getMemberName());
                    doorLockReportRespVO.setRemark(tbDoorlockPassword.getMemberType());
                    doorLockReportRespVO.setPasswordId(tbDoorlockPassword.getThirdPasswordId());
                    doorLockReportRespVO.setPhone(tbDoorlockPassword.getMemberMobile());
                    doorLockReportRespVO.setUserType(tbDoorlockPassword.getMemberType());
                } else {
                    doorLockReportRespVO.setName("——");
                    doorLockReportRespVO.setRemark("动态密码");
                }
            } else {
                doorLockReportRespVO.setName("——");
                doorLockReportRespVO.setRemark("动态密码");
            }
        }
        return ResultModel.createSuccess(tbDeviceOperationPageInfo);
    }

    @Override
    public ResultModel<PageInfo<DoorLockOperationRecord>> getOperationRecord(DoorLockReportReqVO doorLockReportReqVO) {
        TbDeviceDo tbDeviceDo = deviceDataAccess.getDeviceByDeviceNo(doorLockReportReqVO.getDeviceNo());
        if (tbDeviceDo == null) {
            //设备不存在
            return ResultModel.createFail(ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getCode(), ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getMsg());
        }
        PageInfo<DoorLockOperationRecord> doorLockOperationRecordPageInfo = deviceOperationDataAccess.getOperationRecord(doorLockReportReqVO);
        return ResultModel.createSuccess(doorLockOperationRecordPageInfo);
    }

    @Override
    public ResultModel<DoorLockInfo> getDoorlockInfo(String deviceNo) {
        TbDeviceDo tbDeviceDo = deviceDataAccess.getDeviceByDeviceNo(deviceNo);
        if (tbDeviceDo == null) {
            //设备不存在
            return ResultModel.createFail(ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getCode(), ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getMsg());
        }
        DoorLockInfo doorLockInfo = new DoorLockInfo();
        doorLockInfo.setDoorLockNo(tbDeviceDo.getDeviceName());
        doorLockInfo.setPower(tbDeviceDo.getBatteryLevel());
        doorLockInfo.setStatus(tbDeviceDo.getOnlineStatus());
        doorLockInfo.setUpdataTime(Timestamp.valueOf(tbDeviceDo.getUpdateTime()).getTime());
        return ResultModel.createSuccess(doorLockInfo);
    }

    @Override
    public ResultModel<DoorLockInfo> refreshDoorLoclInfo(String deviceNo) throws Exception {
        TbDeviceDo tbDeviceDo = deviceDataAccess.getDeviceByDeviceNo(deviceNo);
        if (tbDeviceDo == null) {
            //设备不存在
            return ResultModel.createFail(ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getCode(), ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getMsg());
        }
        OperateThirdDeviceRequestModel operateThirdDeviceRequestModel = new OperateThirdDeviceRequestModel();
        operateThirdDeviceRequestModel.setDeviceName(tbDeviceDo.getDeviceName());
        operateThirdDeviceRequestModel.setDeviceThirdNoList(Arrays.asList(tbDeviceDo.getDeviceThirdNo()));
        operateThirdDeviceRequestModel.setBrand(tbDeviceDo.getBrandNo());
        operateThirdDeviceRequestModel.setApiNo(tbDeviceDo.getApiNo());

        LOGGER.info("门锁刷新请求参数：{}", JSONObject.toJSONString(operateThirdDeviceRequestModel));
        AccessTokenRequestWrapperModel accessTokenRequestWrapperModel = new AccessTokenRequestWrapperModel();
        accessTokenRequestWrapperModel.setApiNo(operateThirdDeviceRequestModel.getApiNo());
        ResultModel<AccessTokenResponseWrapperModel> resultModel = localAccessTokenServcie.getAccessToken(accessTokenRequestWrapperModel);
        ThirdInstanceService thirdInstanceService = ThirdInstanceFactory.produce(operateThirdDeviceRequestModel.getBrand());
        operateThirdDeviceRequestModel.setAccessToken(resultModel.getData().getAccessToken());
        operateThirdDeviceRequestModel.setLoginName(resultModel.getData().getAppId());
        operateThirdDeviceRequestModel.setLoginKey(resultModel.getData().getAppKey());
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = thirdInstanceService.getDoorLockStatus(operateThirdDeviceRequestModel);
        LOGGER.info("门锁刷新返回参数：{}", JSONObject.toJSONString(operateThirdDeviceResponseModel));

        if (operateThirdDeviceResponseModel.getOperateResult()) {
            DoorLockInfo doorLockInfo = new DoorLockInfo();
            doorLockInfo.setDoorLockNo(tbDeviceDo.getDeviceName());
            doorLockInfo.setPower(operateThirdDeviceResponseModel.getBatteryLevel());
            doorLockInfo.setStatus(operateThirdDeviceResponseModel.getOnlineStatus());
            doorLockInfo.setUpdataTime(System.currentTimeMillis());
            TbDeviceDo tbDeviceDo1 = new TbDeviceDo();
            tbDeviceDo1.setId(tbDeviceDo.getId());
            tbDeviceDo1.setReportTime(LocalDateTime.now());
            tbDeviceDo1.setBatteryLevel(operateThirdDeviceResponseModel.getBatteryLevel());
            tbDeviceDo1.setOnlineStatus(operateThirdDeviceResponseModel.getOnlineStatus());
            deviceDataAccess.updateById(tbDeviceDo1);
            return ResultModel.createSuccess(doorLockInfo);
        } else {
            return ResultModel.createFail(ErrorCodeEnum.MANFGE_REDRESH_ERROR.getCode(), ErrorCodeEnum.MANFGE_REDRESH_ERROR.getMsg());
        }
    }


    @Override
    public ResultModel<AddPasswordModel> frozenPassword(AddPasswordModel addPasswordModel) throws Exception {
        TbDoorlockPassword tbDoorlockPassword = new TbDoorlockPassword();
        tbDoorlockPassword.setDeviceNo(addPasswordModel.getDeviceNo());
        tbDoorlockPassword.setThirdPasswordId(addPasswordModel.getThirdPassId());
        tbDoorlockPassword.setStatus(1);
        tbDoorlockPassword = doorLockPasswordDataAccess.selectTbDoorlockPassword(tbDoorlockPassword);
        if (tbDoorlockPassword.getPasswordStatus() != null && 2 == tbDoorlockPassword.getPasswordStatus()) {
            //密码状态不正确
            return ResultModel.createFail(ErrorCodeEnum.PASSWORD_STATUS_ERROR.getCode(), ErrorCodeEnum.PASSWORD_STATUS_ERROR.getMsg());
        }
        TbDeviceDo tbDeviceDo = deviceDataAccess.getDeviceByDeviceNo(addPasswordModel.getDeviceNo());
        if (tbDeviceDo == null) {
            //设备不存在
            return ResultModel.createFail(ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getCode(), ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getMsg());
        }
        OperateThirdDeviceRequestModel operateThirdDeviceRequestModel = new OperateThirdDeviceRequestModel();
        operateThirdDeviceRequestModel.setBrand(tbDeviceDo.getBrandNo());
        operateThirdDeviceRequestModel.setApiNo(tbDeviceDo.getApiNo());
        operateThirdDeviceRequestModel.setDeviceNo(addPasswordModel.getDeviceNo());
        operateThirdDeviceRequestModel.setDeviceThirdNo(tbDeviceDo.getDeviceThirdNo());
        operateThirdDeviceRequestModel.setPasswordId(addPasswordModel.getThirdPassId());
        TbAccountDo tbAccountDo = tbAccountDataAccess.getThirdApiByApiNo(tbDeviceDo.getApiNo());
        operateThirdDeviceRequestModel.setUserMobile(tbAccountDo.getLoginMobile());
        operateThirdDeviceRequestModel.setTbDoorlockPassword(tbDoorlockPassword);
        operateThirdDeviceRequestModel.setPasswordType(tbDoorlockPassword.getAuthType().toString());
        // todo 这里是硬编码，，，如果是老系统迁移过来的数据密码数据, 需要根据third_password_id删除密码
        if (tbDoorlockPassword.getVolgaId() != null && tbDoorlockPassword.getVolgaId() != -1) {
            try {
                Long.valueOf(tbDoorlockPassword.getThirdPasswordId());
                operateThirdDeviceRequestModel.setMobile(tbDoorlockPassword.getThirdPasswordId());
            } catch (Exception e) {
                operateThirdDeviceRequestModel.setMobile(tbDoorlockPassword.getMemberMobile());
            }
        } else {
            operateThirdDeviceRequestModel.setMobile(tbDoorlockPassword.getMemberMobile());
        }
        operateThirdDeviceRequestModel.setRoomName(addPasswordModel.getRoomName());
        operateThirdDeviceRequestModel.setPasswordStartTime(tbDoorlockPassword.getValidStarttime().getTime());
        operateThirdDeviceRequestModel.setPasswordEndTime(tbDoorlockPassword.getValidEndtime().getTime());

        LOGGER.info("冻结密码请求参数：{}", JSONObject.toJSONString(operateThirdDeviceRequestModel));
        AccessTokenRequestWrapperModel accessTokenRequestWrapperModel = new AccessTokenRequestWrapperModel();
        accessTokenRequestWrapperModel.setApiNo(operateThirdDeviceRequestModel.getApiNo());
        ResultModel<AccessTokenResponseWrapperModel> resultModel = localAccessTokenServcie.getAccessToken(accessTokenRequestWrapperModel);
        ThirdInstanceService thirdInstanceService = ThirdInstanceFactory.produce(operateThirdDeviceRequestModel.getBrand());
        operateThirdDeviceRequestModel.setAccessToken(resultModel.getData().getAccessToken());
        operateThirdDeviceRequestModel.setLoginName(resultModel.getData().getAppId());
        operateThirdDeviceRequestModel.setLoginKey(resultModel.getData().getAppKey());
        operateThirdDeviceRequestModel.setPwdType(tbDoorlockPassword.getPasswordType());
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = thirdInstanceService.frozenDoorLockPassword(operateThirdDeviceRequestModel);
        LOGGER.info("冻结密码返回参数：{}", JSONObject.toJSONString(operateThirdDeviceResponseModel));
        LOGGER.info("biz->冻结密码biz，request:{},response:{}", JSONObject.toJSONString(addPasswordModel), JSONObject.toJSONString(resultModel));
        if (operateThirdDeviceResponseModel.getOperateResult()) {
            //冻结成功落库
            TbDoorlockPassword tbDoorlockPassword1 = new TbDoorlockPassword();
            tbDoorlockPassword1.setId(tbDoorlockPassword.getId());
            tbDoorlockPassword1.setPasswordStatus(operateThirdDeviceResponseModel.getPasswordStatus());
            tbDoorlockPassword1.setThirdPasswordId(operateThirdDeviceResponseModel.getThirdPassId());
            // todo 处理建行一期 & 小水滴6.0迁移数据
            if (tbDoorlockPassword.getVolgaId() != null && tbDoorlockPassword.getVolgaId() != -1) {
                tbDoorlockPassword1.setVolgaId(-1L);
            }
            doorLockPasswordDataAccess.updateById(tbDoorlockPassword1);
            return ResultModel.createSuccess(addPasswordModel);
        } else {
            //冻结失败
            return ResultModel.createFail(ErrorCodeEnum.PASSWORD_FREEZE_ERROR.getCode(), operateThirdDeviceResponseModel.getOperateMessage());
        }
    }


    @Override
    public ResultModel<AddPasswordModel> unfrozenPassword(AddPasswordModel addPasswordModel) throws Exception {
        TbDoorlockPassword tbDoorlockPassword = new TbDoorlockPassword();
        tbDoorlockPassword.setDeviceNo(addPasswordModel.getDeviceNo());
        tbDoorlockPassword.setThirdPasswordId(addPasswordModel.getThirdPassId());
        tbDoorlockPassword.setStatus(1);
        tbDoorlockPassword = doorLockPasswordDataAccess.selectTbDoorlockPassword(tbDoorlockPassword);
        if (tbDoorlockPassword.getPasswordStatus() != null && 0 != tbDoorlockPassword.getPasswordStatus()) {
            //密码状态不正确
            return ResultModel.createFail(ErrorCodeEnum.PASSWORD_STATUS_ERROR.getCode(), ErrorCodeEnum.PASSWORD_STATUS_ERROR.getMsg());
        }
        TbDeviceDo tbDeviceDo = deviceDataAccess.getDeviceByDeviceNo(addPasswordModel.getDeviceNo());
        if (tbDeviceDo == null) {
            //设备不存在
            return ResultModel.createFail(ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getCode(), ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getMsg());
        }
        OperateThirdDeviceRequestModel operateThirdDeviceRequestModel = new OperateThirdDeviceRequestModel();
        operateThirdDeviceRequestModel.setBrand(tbDeviceDo.getBrandNo());
        operateThirdDeviceRequestModel.setApiNo(tbDeviceDo.getApiNo());
        operateThirdDeviceRequestModel.setDeviceNo(addPasswordModel.getDeviceNo());
        operateThirdDeviceRequestModel.setDeviceThirdNo(tbDeviceDo.getDeviceThirdNo());
        operateThirdDeviceRequestModel.setPasswordId(addPasswordModel.getThirdPassId());
        TbAccountDo tbAccountDo = tbAccountDataAccess.getThirdApiByApiNo(tbDeviceDo.getApiNo());
        operateThirdDeviceRequestModel.setUserMobile(tbAccountDo.getLoginMobile());
        operateThirdDeviceRequestModel.setTbDoorlockPassword(tbDoorlockPassword);
        operateThirdDeviceRequestModel.setPasswordType(tbDoorlockPassword.getAuthType().toString());
        operateThirdDeviceRequestModel.setMobile(tbDoorlockPassword.getMemberMobile());
        operateThirdDeviceRequestModel.setRoomName(addPasswordModel.getRoomName());
        operateThirdDeviceRequestModel.setPasswordStartTime(tbDoorlockPassword.getValidStarttime().getTime());
        operateThirdDeviceRequestModel.setPasswordEndTime(tbDoorlockPassword.getValidEndtime().getTime());
        operateThirdDeviceRequestModel.setPwdType(tbDoorlockPassword.getPasswordType());
        ResultModel<OperateThirdDeviceResponseModel> resultModel = this.unfrozenPassword(operateThirdDeviceRequestModel);
        LOGGER.info("biz->解冻密码biz，request:{},response:{}", JSONObject.toJSONString(addPasswordModel), JSONObject.toJSONString(resultModel));
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = resultModel.getData();
        if (operateThirdDeviceResponseModel.getOperateResult()) {
            TbDoorlockPassword tbDoorlockPassword1 = new TbDoorlockPassword();
            tbDoorlockPassword1.setId(tbDoorlockPassword.getId());
            tbDoorlockPassword1.setPasswordStatus(operateThirdDeviceResponseModel.getPasswordStatus());
            tbDoorlockPassword1.setThirdPasswordId(operateThirdDeviceResponseModel.getThirdPassId());
            doorLockPasswordDataAccess.updateById(tbDoorlockPassword1);
            return ResultModel.createSuccess(addPasswordModel);
        } else {
            //解冻密码失败
            return ResultModel.createFail(ErrorCodeEnum.PASSWORD_RELEASE_FREEZE_ERROR.getCode(), operateThirdDeviceResponseModel.getOperateMessage());
        }
    }

    @Override
    public ResultModel<AddPasswordModelVo> deletePassword(AddPasswordModelVo addPasswordModel) throws Exception {
        TbDoorlockPassword tbDoorlockPassword = new TbDoorlockPassword();
        tbDoorlockPassword.setDeviceNo(addPasswordModel.getDeviceNo());
        tbDoorlockPassword.setThirdPasswordId(addPasswordModel.getThirdPassId());
        tbDoorlockPassword.setStatus(1);
        tbDoorlockPassword = doorLockPasswordDataAccess.selectTbDoorlockPassword(tbDoorlockPassword);
        TbDeviceDo tbDeviceDo = deviceDataAccess.getDeviceByDeviceNo(addPasswordModel.getDeviceNo());
        if (tbDeviceDo == null) {
            //设备不存在
            return ResultModel.createFail(ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getCode(), ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getMsg());
        }
        if (tbDoorlockPassword.getPasswordStatus() == null) {
            return ResultModel.createFail(ErrorCodeEnum.CODE_FAIL.getCode(), "密码不存在");
        }
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = null;
        if (tbDoorlockPassword.getPasswordStatus() != 2) {
            OperateThirdDeviceRequestModel operateThirdDeviceRequestModel = new OperateThirdDeviceRequestModel();
            operateThirdDeviceRequestModel.setBrand(tbDeviceDo.getBrandNo());
            operateThirdDeviceRequestModel.setApiNo(tbDeviceDo.getApiNo());
            operateThirdDeviceRequestModel.setDeviceNo(addPasswordModel.getDeviceNo());
            operateThirdDeviceRequestModel.setDeviceThirdNo(tbDeviceDo.getDeviceThirdNo());
            operateThirdDeviceRequestModel.setPasswordId(addPasswordModel.getThirdPassId());
            TbAccountDo tbAccountDo = tbAccountDataAccess.getThirdApiByApiNo(tbDeviceDo.getApiNo());
            operateThirdDeviceRequestModel.setUserMobile(tbAccountDo.getLoginMobile());
            operateThirdDeviceRequestModel.setTbDoorlockPassword(tbDoorlockPassword);
            operateThirdDeviceRequestModel.setPasswordType(tbDoorlockPassword.getAuthType().toString());
            operateThirdDeviceRequestModel.setMobile(tbDoorlockPassword.getMemberMobile());
            operateThirdDeviceRequestModel.setRoomName(addPasswordModel.getRoomName());
            operateThirdDeviceRequestModel.setPwdType(tbDoorlockPassword.getPasswordType());
            ResultModel<OperateThirdDeviceResponseModel> resultModel = this.deletePassword(operateThirdDeviceRequestModel);
            LOGGER.info("biz->删除密码biz，request:{},response:{}", JSONObject.toJSONString(addPasswordModel), JSONObject.toJSONString(resultModel));
            operateThirdDeviceResponseModel = resultModel.getData();
        } else {
            operateThirdDeviceResponseModel = new OperateThirdDeviceResponseModel();
            operateThirdDeviceResponseModel.setOperateResult(true);
        }
        if (operateThirdDeviceResponseModel.getOperateResult()) {
            //删除密码成功 数据库逻辑删除密码  返回成功
            TbDoorlockPassword tbDoorlockPassword1 = new TbDoorlockPassword();
            tbDoorlockPassword1.setId(tbDoorlockPassword.getId());
            tbDoorlockPassword1.setStatus(0);
            if (BrandEnum.YINTONGWULIAN.getBrand().equals(tbDeviceDo.getBrandNo())) {
                tbDoorlockPassword1.setStatus(1);
                tbDoorlockPassword1.setPasswordStatus(4);
            }
            doorLockPasswordDataAccess.updateById(tbDoorlockPassword1);
            // todo 这里是硬编码，，，如果是老系统迁移过来的数据密码数据, 需要根据third_password_id删除密码
            deleteInvalidPassword(tbDoorlockPassword, tbDeviceDo, addPasswordModel.getRoomName());
            return ResultModel.createSuccess(addPasswordModel);
        } else {
            //删除密码失败
            return ResultModel.createFail(ErrorCodeEnum.CODE_FAIL.getCode(), operateThirdDeviceResponseModel.getOperateMessage());
        }
    }

    /**
     * 只针对迁移数据在修改、删除操作的时候需要删除老系统密码
     */
    private void deleteInvalidPassword(TbDoorlockPassword password, TbDeviceDo tbDeviceDo, String roomName) {
        if (password == null) {
            return;
        }

        if (password.getVolgaId() == null || password.getVolgaId() == -1) {
            return;
        }
        LOGGER.info("针对迁移数据删除老系统密码操作: {}", JsonUtils.toJsonString(password));
        if (password.getPasswordStatus() != 2) {
            try {
                OperateThirdDeviceRequestModel operateThirdDeviceRequestModel = new OperateThirdDeviceRequestModel();
                operateThirdDeviceRequestModel.setBrand(tbDeviceDo.getBrandNo());
                operateThirdDeviceRequestModel.setApiNo(tbDeviceDo.getApiNo());
                operateThirdDeviceRequestModel.setDeviceNo(tbDeviceDo.getDeviceNo());
                operateThirdDeviceRequestModel.setDeviceThirdNo(tbDeviceDo.getDeviceThirdNo());
                operateThirdDeviceRequestModel.setPasswordId(password.getThirdPasswordId());
                TbAccountDo tbAccountDo = tbAccountDataAccess.getThirdApiByApiNo(tbDeviceDo.getApiNo());
                operateThirdDeviceRequestModel.setUserMobile(tbAccountDo.getLoginMobile());
                operateThirdDeviceRequestModel.setTbDoorlockPassword(password);
                operateThirdDeviceRequestModel.setPasswordType(password.getAuthType().toString());
                operateThirdDeviceRequestModel.setMobile(password.getThirdPasswordId());
                operateThirdDeviceRequestModel.setRoomName(roomName);
                operateThirdDeviceRequestModel.setPwdType(password.getPasswordType());
                ResultModel<OperateThirdDeviceResponseModel> resultModel = this.deletePassword(operateThirdDeviceRequestModel);
                LOGGER.info("针对迁移数据删除老系统密码操作，request:{},response:{}", JSONObject.toJSONString(password), JSONObject.toJSONString(resultModel));
            } catch (Exception e) {
                LOGGER.info("针对迁移数据删除老系统密码操作失败： ", e);
            }
        }
    }


    @Override
    public ResultModel<AddPasswordModel> updatePassword(AddPasswordModel addPasswordModel) throws Exception {
        if (addPasswordModel.getStartTime() > addPasswordModel.getEndTime() || addPasswordModel.getEndTime() == null || addPasswordModel.getStartTime() == null) {
            //时间格式不正确
            return ResultModel.createFail(ErrorCodeEnum.TIME_FORMAT_IS_ERROR.getCode(), ErrorCodeEnum.TIME_FORMAT_IS_ERROR.getMsg());
        }
        TbDeviceDo tbDeviceDo = deviceDataAccess.getDeviceByDeviceNo(addPasswordModel.getDeviceNo());
        if (tbDeviceDo != null) {
            TbDoorlockPassword tbDoorlockPassword = new TbDoorlockPassword();
            tbDoorlockPassword.setDeviceNo(addPasswordModel.getDeviceNo());
            tbDoorlockPassword.setThirdPasswordId(addPasswordModel.getThirdPassId());
            tbDoorlockPassword.setStatus(1);
            tbDoorlockPassword = doorLockPasswordDataAccess.selectTbDoorlockPassword(tbDoorlockPassword);
//            if (tbDoorlockPassword.getPasswordType() == 0) {
////                long passwordStartTime = Long.parseLong(startTime);
//                long passwordEndTime = Long.parseLong(endTime);
////                addPasswordModel.setStartTime(passwordStartTime);
//                addPasswordModel.setEndTime(passwordEndTime);
//            }
            if (tbDoorlockPassword.getPasswordStatus() != null && 2 != tbDoorlockPassword.getPasswordStatus()) {
                OperateThirdDeviceRequestModel operateThirdDeviceRequestModel = new OperateThirdDeviceRequestModel();
                operateThirdDeviceRequestModel.setDeviceNo(addPasswordModel.getDeviceNo());
                operateThirdDeviceRequestModel.setDeviceThirdNo(tbDeviceDo.getDeviceThirdNo());
                operateThirdDeviceRequestModel.setApiNo(tbDeviceDo.getApiNo());
                operateThirdDeviceRequestModel.setPasswordId(addPasswordModel.getThirdPassId());
                if (StrUtil.isNotBlank(addPasswordModel.getPassword())) {
                    operateThirdDeviceRequestModel.setPasswordContent(addPasswordModel.getPassword());
                } else {
                    operateThirdDeviceRequestModel.setPasswordContent(tbDoorlockPassword.getPassword());
                }
                operateThirdDeviceRequestModel.setPasswordStartTime(addPasswordModel.getStartTime());
                operateThirdDeviceRequestModel.setPasswordEndTime(addPasswordModel.getEndTime());
                operateThirdDeviceRequestModel.setBrand(tbDeviceDo.getBrandNo());
                operateThirdDeviceRequestModel.setTbDoorlockPassword(tbDoorlockPassword);
                TbAccountDo tbAccountDo = tbAccountDataAccess.getThirdApiByApiNo(tbDeviceDo.getApiNo());
                operateThirdDeviceRequestModel.setUserMobile(tbAccountDo.getLoginMobile());
                operateThirdDeviceRequestModel.setPasswordType(tbDoorlockPassword.getAuthType().toString());
                operateThirdDeviceRequestModel.setMobile(addPasswordModel.getMobile());
                operateThirdDeviceRequestModel.setRoomName(addPasswordModel.getRoomName());
                operateThirdDeviceRequestModel.setPwdType(tbDoorlockPassword.getPasswordType());
                // todo 这里是硬编码，，， 如果是老系统迁移过来的数据密码数据, 需要根据third_password_id删除密码。先删除
                deleteInvalidPassword(tbDoorlockPassword, tbDeviceDo, addPasswordModel.getRoomName());
                ResultModel<OperateThirdDeviceResponseModel> resultModel = this.updatePassword(operateThirdDeviceRequestModel);
                LOGGER.info("biz->修改密码biz，request:{},response:{}", JSONObject.toJSONString(addPasswordModel), JSONObject.toJSONString(resultModel));
                OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = resultModel.getData();
                if (operateThirdDeviceResponseModel.getOperateResult()) {
                    //修改密码成功后修改数据库
                    TbDoorlockPassword tbDoorlockPassword1 = new TbDoorlockPassword();
                    tbDoorlockPassword1.setThirdPasswordId(operateThirdDeviceResponseModel.getThirdPassId());
                    tbDoorlockPassword1.setId(tbDoorlockPassword.getId());
                    tbDoorlockPassword1.setValidEndtime(new Date(addPasswordModel.getEndTime()));
                    tbDoorlockPassword1.setValidStarttime(new Date(addPasswordModel.getStartTime()));
                    tbDoorlockPassword1.setPassword(operateThirdDeviceRequestModel.getPasswordContent());
                    tbDoorlockPassword1.setMemberMobile(addPasswordModel.getMobile());
                    tbDoorlockPassword1.setMemberName(addPasswordModel.getUserName());
                    tbDoorlockPassword1.setPasswordStatus(operateThirdDeviceResponseModel.getPasswordStatus());
                    // todo 处理建行一期 & 小水滴6.0迁移数据
                    if (tbDoorlockPassword.getVolgaId() != null && tbDoorlockPassword.getVolgaId() != -1) {
                        tbDoorlockPassword1.setVolgaId(-1L);
                    }
                    doorLockPasswordDataAccess.updateById(tbDoorlockPassword1);
                    Long passwordStartTime = operateThirdDeviceRequestModel.getPasswordStartTime();
                    Date date = new Date(passwordStartTime);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String beginTime = sdf.format(date);

                    Long passwordEndTime = operateThirdDeviceRequestModel.getPasswordEndTime();
                    Date date1 = new Date(passwordEndTime);
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                    String endTime = sdf1.format(date1);

                    Map<String, Object> templateParams = Maps.newHashMap();
                    templateParams.put("password", operateThirdDeviceRequestModel.getPasswordContent());
                    SmsSendSingleToUserReqDTO dto = new SmsSendSingleToUserReqDTO();
                    //获取激活码
                    CommonResult<RoomDoorlockCdkeyVo> doorlockCdkeyResult = this.iotRoomDeviceApi.queryRoomDoorlockCdkeyByDeviceNo(tbDeviceDo.getDeviceNo());
                    LOGGER.info("获取激活码返回值： {}", JsonUtils.toJsonString(doorlockCdkeyResult));
                    String activate_content = "";
                    String expiration_date = "";
                    if (doorlockCdkeyResult.isSuccess()) {
                        RoomDoorlockCdkeyVo roomDoorlockCdkeyVo = doorlockCdkeyResult.getData();
                        if (roomDoorlockCdkeyVo != null && StrUtil.isNotEmpty(roomDoorlockCdkeyVo.getCdkey())) {
                            activate_content = String.format(CommonConstants.ACTIVATE_CONTENT, roomDoorlockCdkeyVo.getCdkey());
                        }
                    }
                    if (tbDoorlockPassword.getPasswordType() != 0) {
                        //非永久密码
                        expiration_date = String.format(CommonConstants.EXPIRATION_DATE, beginTime, endTime);
                    }
                    if (addPasswordModel.getGate() == null || !addPasswordModel.getGate()) {
                        //门锁密码模板
                        dto.setTemplateCode("iot-sms-lockpassword-1");
                    } else {
                        //大门锁密码模板
                        dto.setTemplateCode("iot-sms-lockpassword");
                    }
                    templateParams.put("activate_content", activate_content);
                    // 短信模板审核不通过activate_content改为name
                    templateParams.put("name", activate_content);
                    templateParams.put("expiration_date", expiration_date);
                    dto.setTemplateParams(templateParams);
                    dto.setMobile(operateThirdDeviceRequestModel.getMobile());
                    smsFeignService.sendSingleSmsToMember(dto);
                    return ResultModel.createSuccess(addPasswordModel);
                } else {
                    //密码修改失败
                    return ResultModel.createFail(ErrorCodeEnum.PASSWORD_UPDATE_ERROR.getCode(), operateThirdDeviceResponseModel.getOperateMessage());
                }
            } else {
                //密码已过期或不存在
                return ResultModel.createFail(ErrorCodeEnum.PASSWORD_STATUS_ERROR.getCode(), ErrorCodeEnum.PASSWORD_STATUS_ERROR.getMsg());
            }
        } else {
            //设备不存在
            return ResultModel.createFail(ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getCode(), ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getMsg());
        }
    }


    @Override
    @Transactional
    public ResultModel<AddPasswordModel> addPassword(AddPasswordModel addPasswordModel) throws Exception {
        if (ObjectUtil.isEmpty(addPasswordModel.getPasswordType())) {
            addPasswordModel.setPasswordType(2);
        }
//        if (addPasswordModel.getPasswordType() == 0) {
////            long passwordStartTime = Long.parseLong(startTime);
//            long passwordEndTime = Long.parseLong(endTime);
////            addPasswordModel.setStartTime(passwordStartTime);
//            addPasswordModel.setEndTime(passwordEndTime);
//        }
        //验证同一个手机号只能添加一个密码
        TbDoorlockPassword doorlock = new TbDoorlockPassword();
        doorlock.setMemberMobile(addPasswordModel.getMobile());
        doorlock.setStatus(1);
        doorlock.setDeviceNo(addPasswordModel.getDeviceNo());
        Long countNum = doorLockPasswordDataAccess.getCountNum(doorlock);
        LOGGER.info("是否存在同一个手机号下发过密码：" + countNum);
        if (countNum >= 1) {
            return ResultModel.createFail(ErrorCodeEnum.PASSWAORD_PHONE_ERROR.getCode(), ErrorCodeEnum.PASSWAORD_PHONE_ERROR.getMsg());
        }
        if (addPasswordModel.getStartTime() > addPasswordModel.getEndTime() || addPasswordModel.getEndTime() == null || addPasswordModel.getStartTime() == null) {
            //时间格式不正确
            return ResultModel.createFail(ErrorCodeEnum.TIME_FORMAT_IS_ERROR.getCode(), ErrorCodeEnum.TIME_FORMAT_IS_ERROR.getMsg());
        }
        TbDeviceDo tbDeviceDo = deviceDataAccess.getDeviceByDeviceNo(addPasswordModel.getDeviceNo());
        if (tbDeviceDo == null) {
            return ResultModel.createFail(ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getCode(), ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getMsg());
        }
        addPasswordModel.setApiNo(tbDeviceDo.getApiNo());
        addPasswordModel.setBrand(tbDeviceDo.getBrandNo());
        addPasswordModel.setDeviceThirdNo(tbDeviceDo.getDeviceThirdNo());
        List<TbDoorlockPassword> tbDoorlockPasswords = doorLockPasswordDataAccess.findByDeviceOrderBy(addPasswordModel.getDeviceNo());
        String thirdPassId = addPasswordModel.getMobile();
        thirdPassId = getThirdPasswordIdForKunShan(tbDeviceDo, thirdPassId, addPasswordModel.getAuthType(), tbDoorlockPasswords);
        addPasswordModel.setThirdPassId(thirdPassId);
        TbAccountDo tbAccountDo = tbAccountDataAccess.getThirdApiByApiNo(tbDeviceDo.getApiNo());
        addPasswordModel.setUserMobile(tbAccountDo.getLoginMobile());
        LOGGER.info("添加密码请求参数：{}", JSONObject.toJSONString(addPasswordModel));
        AccessTokenRequestWrapperModel accessTokenRequestWrapperModel = new AccessTokenRequestWrapperModel();
        accessTokenRequestWrapperModel.setApiNo(addPasswordModel.getApiNo());
        ResultModel<AccessTokenResponseWrapperModel> resultModel = localAccessTokenServcie.getAccessToken(accessTokenRequestWrapperModel);
        ThirdInstanceService thirdInstanceService = ThirdInstanceFactory.produce(addPasswordModel.getBrand());
        OperateThirdDeviceRequestModel operateThirdDeviceRequestModel = new OperateThirdDeviceRequestModel();
        operateThirdDeviceRequestModel.setAccessToken(resultModel.getData().getAccessToken());
        operateThirdDeviceRequestModel.setDeviceNo(addPasswordModel.getDeviceNo());
        operateThirdDeviceRequestModel.setDeviceThirdNo(addPasswordModel.getDeviceThirdNo());
        operateThirdDeviceRequestModel.setMobile(addPasswordModel.getMobile());
        operateThirdDeviceRequestModel.setPasswordId(addPasswordModel.getMobile());
        operateThirdDeviceRequestModel.setPasswordContent(addPasswordModel.getPassword());
        operateThirdDeviceRequestModel.setPasswordStartTime(addPasswordModel.getStartTime());
        operateThirdDeviceRequestModel.setPasswordEndTime(addPasswordModel.getEndTime());
        operateThirdDeviceRequestModel.setLoginName(resultModel.getData().getAppId());
        operateThirdDeviceRequestModel.setLoginKey(resultModel.getData().getAppKey());
        operateThirdDeviceRequestModel.setPasswordType("1");
        operateThirdDeviceRequestModel.setRoomName(addPasswordModel.getRoomName());
        operateThirdDeviceRequestModel.setUserName(addPasswordModel.getUserName());
        operateThirdDeviceRequestModel.setUserMobile(addPasswordModel.getUserMobile());
        operateThirdDeviceRequestModel.setGate(addPasswordModel.getGate());
        operateThirdDeviceRequestModel.setPwdType(addPasswordModel.getPasswordType());
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = thirdInstanceService.addDoorLockPassword(operateThirdDeviceRequestModel);
        LOGGER.info("添加密码返回参数：{}", JSONObject.toJSONString(operateThirdDeviceResponseModel));
        if (operateThirdDeviceResponseModel.getOperateResult()) {
            //成功后落库完事
            TbDoorlockPassword tbDoorlockPassword = new TbDoorlockPassword();
            String password = "";
            //蚂蚁第三方接口密码是由设备厂商返回的，获取到密码发送短信到租户手机上,密码标识入库用接口返回的
            if (tbDeviceDo.getBrandNo().startsWith("ant")) {
                password = operateThirdDeviceResponseModel.getPasswordContent();
                thirdPassId = operateThirdDeviceResponseModel.getThirdPassId();
            }
            //海康、果加、云丁、天固、海联、同创第三方接口密码ID都是由第三方返回
            else if (tbDeviceDo.getBrandNo().equals("haikang") || tbDeviceDo.getBrandNo().equals("guojia") || tbDeviceDo.getBrandNo().equals("yintongwulian")
                    || tbDeviceDo.getBrandNo().equals("yunding") || tbDeviceDo.getBrandNo().equals("tiangu")
                    || tbDeviceDo.getBrandNo().equals("hailian") || tbDeviceDo.getBrandNo().equals("tongchuang")
                    || tbDeviceDo.getBrandNo().equalsIgnoreCase("danbei") || tbDeviceDo.getBrandNo().equalsIgnoreCase("zhixin") || tbDeviceDo.getBrandNo().equalsIgnoreCase("wota")
                    || tbDeviceDo.getBrandNo().equalsIgnoreCase("ximeng") || tbDeviceDo.getBrandNo().equalsIgnoreCase("kunshan") || tbDeviceDo.getBrandNo().equalsIgnoreCase("newwota")) {
                if (tbDeviceDo.getBrandNo().equalsIgnoreCase(BrandEnum.KUNSHAN.getBrand()) &&
                        addPasswordModel.getAuthType().compareTo(Integer.parseInt(PasswordTypeEnum.OFFLINE_PASSWORD.getTypeCode())) >= 0) {
                    // 对琨山离线密码进行额外处理
                    password = operateThirdDeviceResponseModel.getPasswordContent();
                    operateThirdDeviceResponseModel.setPasswordStatus(1);
                } else {
                    password = addPasswordModel.getPassword();
                    thirdPassId = operateThirdDeviceResponseModel.getThirdPassId();
                }
            } else {
                password = addPasswordModel.getPassword();
            }
            LOGGER.info("品牌{},密码{},密码id{}", tbDeviceDo.getBrandNo(), password, thirdPassId);
            tbDoorlockPassword.setPassword(password);
            tbDoorlockPassword.setThirdPasswordId(thirdPassId);
            tbDoorlockPassword.setDeviceNo(addPasswordModel.getDeviceNo());
            tbDoorlockPassword.setMemberType(addPasswordModel.getUserType());
            tbDoorlockPassword.setMemberMobile(addPasswordModel.getMobile());
            tbDoorlockPassword.setMemberName(addPasswordModel.getUserName());
            tbDoorlockPassword.setPasswordStatus(operateThirdDeviceResponseModel.getPasswordStatus());
            tbDoorlockPassword.setValidStarttime(new Date(addPasswordModel.getStartTime()));
            tbDoorlockPassword.setValidEndtime(new Date(addPasswordModel.getEndTime()));
            tbDoorlockPassword.setStatus(1);
            tbDoorlockPassword.setAuthType(1);
            tbDoorlockPassword.setOperatorName(addPasswordModel.getOperatorName());
            tbDoorlockPassword.setPasswordType(addPasswordModel.getPasswordType());
            doorLockPasswordDataAccess.save(tbDoorlockPassword);
            addPasswordModel.setThirdPassId(thirdPassId);
            addPasswordModel.setPassword(password);
            return ResultModel.createSuccess(addPasswordModel);
        } else {
            return ResultModel.createFail(ErrorCodeEnum.PASSWAORD_ADD_ERROR.getCode(), operateThirdDeviceResponseModel.getOperateMessage());
        }
    }

    @Override
    public ResultModel<List<AddPasswordModel>> getPasswordList(String deviceNo, String mobile) {
        TbDeviceDo tbDeviceDo = deviceDataAccess.getDeviceByDeviceNo(deviceNo);
        if (tbDeviceDo == null) {
            return ResultModel.createFail(ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getCode(), ErrorCodeEnum.DEVICE_NO_NOT_EXIST.getMsg());
        }
        //sql排序
        List<AddPasswordModel> addPasswordModels = new ArrayList<>();
        List<TbDoorlockPassword> tbDoorlockPasswords = doorLockPasswordDataAccess.findByDeviceAndCreateUser(deviceNo, mobile);
        addPasswordModels = passwordDeal(tbDoorlockPasswords, false, tbDeviceDo);
        LOGGER.info("门锁密码列表返回############,List<AddPasswordModel> {}", JSONObject.toJSONString(addPasswordModels));
        return ResultModel.createSuccess(addPasswordModels);
    }


    public List<AddPasswordModel> passwordDeal(List<TbDoorlockPassword> passwordModels, Boolean flag, TbDeviceDo tbDeviceDo) {
        List<AddPasswordModel> addPasswordModels = new ArrayList<>();
        Iterator<TbDoorlockPassword> iterator = passwordModels.iterator();
        Long nowTime = System.currentTimeMillis();
        TbAccountDo tbAccountDo = tbAccountDataAccess.getThirdApiByApiNo(tbDeviceDo.getApiNo());
        while (iterator.hasNext()) {
            TbDoorlockPassword tbDoorlockPassword = iterator.next();
            AddPasswordModel addPasswordModel = new AddPasswordModel();
            addPasswordModel.setRemark(tbDoorlockPassword.getMemberType());
            addPasswordModel.setUserName(tbDoorlockPassword.getMemberName());
            addPasswordModel.setMobile(tbDoorlockPassword.getMemberMobile());
            addPasswordModel.setAuthType(tbDoorlockPassword.getAuthType());
            addPasswordModel.setUserType(tbDoorlockPassword.getMemberType());
            addPasswordModel.setPassword(tbDoorlockPassword.getPassword());
            addPasswordModel.setPasswordType(tbDoorlockPassword.getPasswordType());
            //密码状态:0:冻结 1:生效 2:过期 3:未生效 4:执行中 5:添加失败
            if (tbDoorlockPassword.getPasswordStatus() == 1 && tbDoorlockPassword.getValidEndtime().getTime() < nowTime) {
                //若查出该门锁品牌提供商为“kunshan”或者“NEWWOTA",则调用琨山或新沃塔API删除密码
                if (tbDeviceDo.getBrandNo().equals(BrandEnum.KUNSHAN.getBrand()) || tbDeviceDo.getBrandNo().equals(BrandEnum.NEWWOTA.getBrand())) {
                    OperateThirdDeviceRequestModel operateThirdDeviceRequestModel = new OperateThirdDeviceRequestModel();
                    operateThirdDeviceRequestModel.setBrand(tbDeviceDo.getBrandNo());
                    operateThirdDeviceRequestModel.setApiNo(tbDeviceDo.getApiNo());
                    operateThirdDeviceRequestModel.setDeviceNo(tbDeviceDo.getDeviceNo());
                    operateThirdDeviceRequestModel.setDeviceThirdNo(tbDeviceDo.getDeviceThirdNo());
                    operateThirdDeviceRequestModel.setPasswordId(tbDoorlockPassword.getThirdPasswordId());
                    operateThirdDeviceRequestModel.setUserMobile(tbAccountDo.getLoginMobile());
                    operateThirdDeviceRequestModel.setTbDoorlockPassword(tbDoorlockPassword);
                    operateThirdDeviceRequestModel.setPasswordType(tbDoorlockPassword.getAuthType().toString());
                    operateThirdDeviceRequestModel.setMobile(tbDoorlockPassword.getMemberMobile());
                    //异步调用第三方接口
                    singleCoreThreadExecutor.execute(new Runnable() {
                        @Override
                        public void run() {
                            ResultModel<OperateThirdDeviceResponseModel> resultModel = null;
                            try {
                                resultModel=deletePassword(operateThirdDeviceRequestModel);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                            LOGGER.info("biz->删除密码biz，request:{},response:{}", JSONObject.toJSONString(addPasswordModel), JSONObject.toJSONString(resultModel));
                        }
                    });
//                    ResultModel<OperateThirdDeviceResponseModel> resultModel = null;
//                    try {
//                        resultModel = deletePassword(operateThirdDeviceRequestModel);
//                    } catch (Exception e) {
//                        throw new RuntimeException(e);
//                    }
//                    LOGGER.info("biz->删除密码biz，request:{},response:{}", JSONObject.toJSONString(addPasswordModel), JSONObject.toJSONString(resultModel));
                    continue;
                }
                //密码已过期 修改密码状态
                addPasswordModel.setPasswordStatus(2);
                TbDoorlockPassword tbDoorlockPassword1 = new TbDoorlockPassword();
                tbDoorlockPassword1.setId(tbDoorlockPassword.getId());
                tbDoorlockPassword1.setPasswordStatus(2);
                doorLockPasswordDataAccess.updateById(tbDoorlockPassword1);
                if (flag) {
                    iterator.remove();
                }
            } else if ((tbDoorlockPassword.getPasswordStatus() == 2 || tbDoorlockPassword.getPasswordStatus() == 3) && tbDoorlockPassword.getValidStarttime().getTime() < nowTime && tbDoorlockPassword.getValidEndtime().getTime() > nowTime) {

                //密码已生效 修改密码状态
                addPasswordModel.setPasswordStatus(1);
                TbDoorlockPassword tbDoorlockPassword1 = new TbDoorlockPassword();
                tbDoorlockPassword1.setId(tbDoorlockPassword.getId());
                tbDoorlockPassword1.setPasswordStatus(1);
                doorLockPasswordDataAccess.updateById(tbDoorlockPassword1);
                if (flag) {
                    iterator.remove();
                }


            } else if (tbDoorlockPassword.getPasswordStatus() == 1 && tbDoorlockPassword.getValidStarttime().getTime() > nowTime) {
                //密码未生效 修改密码状态
                addPasswordModel.setPasswordStatus(3);
                TbDoorlockPassword tbDoorlockPassword1 = new TbDoorlockPassword();
                tbDoorlockPassword1.setId(tbDoorlockPassword.getId());
                tbDoorlockPassword1.setPasswordStatus(3);
                doorLockPasswordDataAccess.updateById(tbDoorlockPassword1);
                if (flag) {
                    iterator.remove();
                }
            } else if (tbDoorlockPassword.getPasswordStatus() == 2) {
                //调用银通物联删除密码接口
                OperateThirdDeviceRequestModel operateThirdDeviceRequestModel = new OperateThirdDeviceRequestModel();
                operateThirdDeviceRequestModel.setPasswordId(tbDoorlockPassword.getId().toString());
                operateThirdDeviceRequestModel.setApiNo(tbDeviceDo.getApiNo());
                operateThirdDeviceRequestModel.setBrand(tbDeviceDo.getBrandNo());
                operateThirdDeviceRequestModel.setDeviceThirdNo(tbDeviceDo.getDeviceThirdNo());
                operateThirdDeviceRequestModel.setPasswordContent(tbDoorlockPassword.getPassword());
                operateThirdDeviceRequestModel.setPwdType(tbDoorlockPassword.getPasswordType());
                try {
                    this.deletePassword(operateThirdDeviceRequestModel);
                } catch (Exception e) {
                    LOGGER.error("主动删除过期密码报错", e);
                }
            } else {
                //未过期也未生效返回当前状态
                addPasswordModel.setPasswordStatus(tbDoorlockPassword.getPasswordStatus());
            }
            if (flag) {
                addPasswordModel.setPassword(tbDoorlockPassword.getPassword());
            }
            addPasswordModel.setDeviceNo(tbDoorlockPassword.getDeviceNo());
            addPasswordModel.setPasswordStatus(tbDoorlockPassword.getPasswordStatus());
            addPasswordModel.setStartTime(tbDoorlockPassword.getValidStarttime().getTime());
            addPasswordModel.setEndTime(tbDoorlockPassword.getValidEndtime().getTime());
            addPasswordModel.setThirdPassId(tbDoorlockPassword.getThirdPasswordId());
            addPasswordModel.setOperatorName(tbDoorlockPassword.getOperatorName());
            addPasswordModel.setCreateTime(tbDoorlockPassword.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            addPasswordModels.add(addPasswordModel);
        }
        return addPasswordModels;
    }



    private String getThirdPasswordIdForKunShan(TbDeviceDo tbDeviceDo, String thirdPassId, int authType, List<
            TbDoorlockPassword> tbDoorLockPasswords) {
        if (BrandEnum.KUNSHAN.getBrand().equals(tbDeviceDo.getBrandNo())) {
            if (CollectionUtil.isEmpty(tbDoorLockPasswords)) {
                return "0";
            }
            String uuid = UUID.randomUUID().toString();
            int finalTempAuthType = authType;
            // 琨山离线密码不进行回调,故以我们自己为准.
            if (!PasswordTypeEnum.OFFLINE_PASSWORD.getTypeCode().equals(authType)) {
                return uuid;
            }
            List<TbDoorlockPassword> authTypeHistoryDoorLockPasswords = tbDoorLockPasswords.stream()
                    .filter((tbDoorlockPassword -> tbDoorlockPassword.getAuthType() == finalTempAuthType &&
                            tbDoorlockPassword.getStatus().equals(BusinessConstant.DOOR_LOCK_PASSWORD_RECORD_STATUS_VALID)))
                    .collect(Collectors.toList());
            if (CollectionUtil.isEmpty(authTypeHistoryDoorLockPasswords)) {
                thirdPassId = "0";
            } else {
                // 按照类型倒序后获取第一个
                TbDoorlockPassword last = authTypeHistoryDoorLockPasswords.stream().sorted(Comparator.comparing(TbDoorlockPassword::getId).reversed()).findFirst().get();
                try {
                    thirdPassId = String.valueOf(Integer.parseInt(last.getThirdPasswordId()) + 1);
                } catch (NumberFormatException e) {
                    // never happen
                    LOGGER.error("门锁 {} 离线密码尚未确认就申请新密码", tbDeviceDo.getDeviceName());
                }
            }
        }
        return thirdPassId;
    }
}
